//
//  Project_Step1ViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/4.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "ProjectSelectTempletViewController.h"
#import "DefaultStyleTableViewCell.h"
#import "Project_TabViewController.h"
#import "Project_Step1ViewController.h"
#import "Project_Step2ViewController.h"
#import "Project_Step3ViewController.h"
#import "BottomActionView.h"
#import "ProjectData.h"
#import "ProjectTemplateData.h"
#import "ProjectManager.h"
#import <MBProgressHUD.h>
#import "RoomData.h"
#import "ProjectContentViewController.h"

@interface ProjectSelectTempletViewController () {
    MBProgressHUD *HUD;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomActionView *footerView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,assign) NSInteger selectedIndex;

@end

@implementation ProjectSelectTempletViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
//    [self loadData];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
//    ProjectTemplateData *item1 = [ProjectTemplateData new];
//    [item1 setTitle:@"一室一厅"];
//    [item1 setComment:@"一个客厅，一个卧室"];
//    [self.dataSource addObject:item1];
//    ProjectTemplateData *item2 = [ProjectTemplateData new];
//    [item2 setTitle:@"两室一厅"];
//    [item2 setComment:@"一个客厅，一个餐厅，两个卧室"];
//    [self.dataSource addObject:item2];
//    ProjectTemplateData *item3 = [ProjectTemplateData new];
//    [item3 setTitle:@"两室两厅"];
//    [item3 setComment:@"一个客厅，一个餐厅，两个卧室"];
//    [self.dataSource addObject:item3];
//    ProjectTemplateData *item4 = [ProjectTemplateData new];
//    [item4 setTitle:@"三室两厅"];
//    [item4 setComment:@"一个客厅，一个餐厅，两个卧室，一个书房"];
//    [self.dataSource addObject:item4];
//    ProjectTemplateData *item5 = [ProjectTemplateData new];
//    [item5 setTitle:@"四室两厅"];
//    [item5 setComment:@"一个客厅，一个餐厅，三个卧室"];
//    [self.dataSource addObject:item5];
//    ProjectTemplateData *item6 = [ProjectTemplateData new];
//    [item6 setTitle:@"五室两厅"];
//    [item6 setComment:@"一个客厅，一个餐厅，三个卧室，一个书房"];
//    [self.dataSource addObject:item6];
//    ProjectTemplateData *item7 = [ProjectTemplateData new];
//    [item7 setTitle:@"别墅"];
//    [item7 setComment:@"一个客厅，一个餐厅，四个卧室，一个书房，一个工人房"];
//    [self.dataSource addObject:item7];
//    ProjectTemplateData *item8 = [ProjectTemplateData new];
//    [item8 setTitle:@"自定义"];
//    [item8 setComment:@"空白项目，不含任何房间和系统"];
//    [self.dataSource addObject:item8];
    self.selectedIndex = -1;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.footerView updateCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
}


#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"选择房型模板";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //底部的上一步，下一步按钮
    self.footerView = [[BottomActionView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    __block ProjectSelectTempletViewController *tmp = (ProjectSelectTempletViewController*)self;
    [self.footerView addLeftBtnBlock:^(id obj) {
        [[ProjectManager manager]goLastPage];
        [tmp.navigationController popViewControllerAnimated:YES];   
    }];
    [self.footerView addRightBtnBlock:^(id obj) {
        if (self.selectedIndex < 0) {
            [Tools showMessageCenter:@"请选择房型模板"];
            return;
        }
        [tmp applyRooms:^(BOOL result) {
            if (result) {
                [[ProjectManager manager]goNextPage];
                Project_Step2ViewController *view = [Project_Step2ViewController new];
                [tmp.navigationController pushViewController:view animated:YES];
            } else {
                [Tools showMessageCenter:@"房间模版设置失败！"];
            }
        }];//设置模版房间
        
    }];
    [self.footerView setLeftBtnTitle:@"上一步" andRightBtnTitle:@"下一步" andCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
    [self.view addSubview:self.footerView];
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavBottom] style:UITableViewStylePlain];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_ROOMS_TEMPLATE paramDic:param resultClass:[ProjectTemplateData class] success:^(ProjectTemplateData *obj) {
        [self.tableView.mj_header endRefreshing];
        [self.dataSource removeAllObjects];
        if (obj.result && obj.result.count > 0) {
            [self.dataSource addObjectsFromArray:obj.result];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.dataSource removeAllObjects];
        [self.tableView reloadData];
        CMLog(@"获取房间模版失败：%@", error);
    }];
}


- (void)applyRooms:(void (^)(BOOL))result {
    ProjectTemplateData *date = [self.dataSource objectAtIndex:self.selectedIndex];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@(date.template_id) forKey:@"template_id"];
    [params setValue:kProject.project_id forKey:@"project_id"];
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_ROOMS_TEMPLATE_APPLY token:[AccountManager manager].token paramDic:params resultClass:[RoomData class] success:^(RoomData *obj) {
        //oc对象归档
        if (obj.result != nil && obj.result.count > 0) {
            kProject.rooms = [obj.result mutableCopy];
        }
        kProject.template_bind = 1;
        result(YES);
    } failure:^(NSError *error) {
        result(NO);
    }];
}

#pragma mark - 事件响应函数
/**
 *  直接跳转到项目页面
 */
-(void)onBackToProject{
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[Project_TabViewController class]]) {
            [(Project_TabViewController*)tmp refreshData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"ProjectModuleCell";
    DefaultStyleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[DefaultStyleTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    if (self.selectedIndex == indexPath.row) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    ProjectTemplateData *item = [self.dataSource objectAtIndex:indexPath.row];
    cell.textLabel.text = item.title;
    cell.textLabel.textColor = CM_BLUE_COLOR;
    cell.detailTextLabel.text = item.comment;
    cell.detailTextLabel.hidden = NO;
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.selectedIndex = indexPath.row;
    [self.tableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CELL_HEIGHT;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
